<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>血糖管理系统</title>
    <style>
        /* 基础样式 */
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        header {
            background: linear-gradient(135deg, #4b6cb7 0%, #182848 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        h1, h2, h3 {
            margin-bottom: 15px;
        }
        
        /* 卡片样式 */
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        /* 按钮样式 */
        .btn {
            display: inline-block;
            padding: 10px 20px;
            background-color: #4b6cb7;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        
        .btn:hover {
            background-color: #3a559d;
        }
        
        .btn-success {
            background-color: #28a745;
        }
        
        .btn-success:hover {
            background-color: #218838;
        }
        
        .btn-danger {
            background-color: #dc3545;
        }
        
        .btn-danger:hover {
            background-color: #c82333;
        }
        
        .btn-warning {
            background-color: #ffc107;
            color: #212529;
        }
        
        .btn-warning:hover {
            background-color: #e0a800;
        }
        
        .btn-info {
            background-color: #17a2b8;
        }
        
        .btn-info:hover {
            background-color: #138496;
        }
        
        /* 表单样式 */
        .form-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
        }
        
        input, select, textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        
        /* 表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        
        /* 视图控制 */
        .view {
            display: none;
            padding: 20px;
        }
        
        .active {
            display: block;
        }
        
        /* 导航 */
        .nav {
            display: flex;
            background-color: #f8f9fa;
            border-bottom: 1px solid #ddd;
        }
        
        .nav-item {
            padding: 15px 20px;
            cursor: pointer;
            border-bottom: 3px solid transparent;
        }
        
        .nav-item.active {
            border-bottom-color: #4b6cb7;
            background-color: white;
            font-weight: 600;
        }
        
        /* 响应式 */
        @media (max-width: 768px) {
            .nav {
                flex-direction: column;
            }
            
            .card {
                padding: 15px;
            }
            
            .data-section {
                overflow-x: auto;
            }
        }
        
        /* 图表容器 */
        .chart-container {
            height: 400px;
            margin-top: 20px;
        }
        
        /* 用户卡片 */
        .user-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            background: white;
        }
        
        .user-card h4 {
            margin-bottom: 10px;
            color: #4b6cb7;
        }
        
        .qr-code {
            text-align: center;
            margin: 10px 0;
        }
        
        /* 模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            max-width: 500px;
            width: 90%;
            text-align: center;
        }
        
        .modal h3 {
            margin-bottom: 20px;
            color: #4b6cb7;
        }
        
        .close {
            position: absolute;
            top: 15px;
            right: 15px;
            font-size: 24px;
            cursor: pointer;
        }
        
        /* 登录页面 */
        .login-container {
            max-width: 400px;
            margin: 50px auto;
            padding: 30px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .login-form {
            margin-top: 20px;
        }
        
        /* 工具提示 */
        .tooltip {
            position: relative;
            display: inline-block;
            border-bottom: 1px dotted #ccc;
            cursor: help;
        }
        
        .tooltip .tooltiptext {
            visibility: hidden;
            width: 200px;
            background-color: #555;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 5px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            margin-left: -100px;
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }
        
        /* 血糖数据区域样式 */
        .data-section {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        
        .data-section h4 {
            color: #4b6cb7;
            margin-bottom: 10px;
            border-bottom: 1px solid #ddd;
            padding-bottom: 5px;
        }
        
        /* 设置区域样式 */
        .settings-group {
            margin-bottom: 25px;
        }
        
        .settings-group h4 {
            margin-bottom: 10px;
            color: #4b6cb7;
        }
        
        /* 选项卡样式 */
        .tab-content {
            margin-top: 20px;
        }
        
        .tab-pane {
            display: none;
        }
        
        .tab-pane.active {
            display: block;
        }
        
        /* 选项卡导航 */
        .tab-nav {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 20px;
        }
        
        .tab-link {
            padding: 10px 20px;
            cursor: pointer;
            border-bottom: 3px solid transparent;
        }
        
        .tab-link.active {
            border-bottom-color: #4b6cb7;
            font-weight: 600;
        }
        
        /* 上传状态提示 */
        .upload-status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            display: none;
        }
        
        .upload-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .upload-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        /* 服务器设置区域 */
        .server-settings {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        /* 加载动画 */
        .loader {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
            display: none;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 微信提示 */
        .wechat-tip {
            background-color: #fffbe6;
            border: 1px solid #ffe58f;
            border-radius: 4px;
            padding: 10px;
            margin: 10px 0;
            color: #876800;
        }

        /* 部署提示 */
        .deploy-tip {
            background-color: #e6f7ff;
            border: 1px solid #91d5ff;
            border-radius: 4px;
            padding: 15px;
            margin: 15px 0;
            color: #0050b3;
        }
        
        .deploy-tip h4 {
            color: #0050b3;
            margin-bottom: 10px;
        }
        
        .deploy-tip ul {
            margin: 10px 0;
            padding-left: 20px;
        }
        
        .deploy-tip code {
            background-color: #f5f5f5;
            padding: 2px 5px;
            border-radius: 3px;
            font-family: monospace;
        }

        /* 编辑记录模态框样式 */
        .edit-modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            max-width: 800px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        /* 客户端数据查看样式 */
        .client-data-view {
            margin-top: 20px;
        }
        
        .client-data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        
        .client-data-table th, 
        .client-data-table td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        .client-data-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        
        .no-data {
            text-align: center;
            padding: 20px;
            color: #666;
        }
    </style>
</head>
<body>
    <!-- 登录界面 -->
    <div id="loginView" class="login-container">
        <h2 class="text-center">血糖管理系统</h2>
        <div class="login-form">
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" value="admin" placeholder="请输入用户名">
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" placeholder="请输入密码">
            </div>
            <button id="loginBtn" class="btn" style="width: 100%">登录</button>
            <p class="text-center" style="margin-top: 20px; color: #666;">
                默认账号: admin / admin
            </p>
        </div>
    </div>

    <!-- 主应用界面 -->
    <div id="appView" class="container" style="display: none;">
        <header>
            <h1>血糖管理系统</h1>
            <p>便捷管理客户血糖数据，生成专属二维码</p>
        </header>
        
        <div class="nav">
            <div class="nav-item active" data-view="userManager">客户管理</div>
            <div class="nav-item" data-view="dataView">数据查看</div>
            <div class="nav-item" data-view="dataAnalysis">数据分析</div>
            <div class="nav-item" data-view="settingsView">系统设置</div>
            <div style="margin-left: auto; padding: 15px 20px;">
                <button id="logoutBtn" class="btn btn-danger">退出登录</button>
            </div>
        </div>
        
        <!-- 客户管理视图 -->
        <div id="userManager" class="view active">
            <div class="deploy-tip">
                <h4>二维码访问提示</h4>
                <p>要使二维码能被手机扫描访问，您需要：</p>
                <ul>
                    <li>将本系统部署到服务器或使用本地HTTP服务器</li>
                    <li>确保通过HTTP/HTTPS协议访问本页面，而不是file://协议</li>
                </ul>
                <p>快速测试方法：使用Python启动本地服务器</p>
                <code>python -m http.server 8000</code>
                <p>然后通过 <code>http://localhost:8000</code> 访问</p>
            </div>
            
            <div class="card">
                <h3>添加新客户</h3>
                <div style="display: flex; gap: 10px;">
                    <input type="text" id="newUserName" placeholder="输入客户姓名" style="flex: 1;">
                    <button id="addUserBtn" class="btn btn-success">添加客户</button>
                </div>
            </div>
            
            <div class="card">
                <h3>客户列表</h3>
                <div id="userList">
                    <!-- 用户列表将在这里动态生成 -->
                </div>
            </div>
        </div>
        
        <!-- 数据查看视图 -->
        <div id="dataView" class="view">
            <div class="card">
                <h3>血糖数据记录</h3>
                <div class="form-group">
                    <label for="selectUser">选择客户</label>
                    <select id="selectUser">
                        <option value="">请选择客户</option>
                    </select>
                </div>
                
                <div class="data-section">
                    <table id="dataTable">
                        <thead>
                            <tr>
                                <th>日期</th>
                                <th>空腹血糖</th>
                                <th>早餐后1小时</th>
                                <th>早餐后2小时</th>
                                <th>午餐前</th>
                                <th>午餐后1小时</th>
                                <th>午餐后2小时</th>
                                <th>晚餐前</th>
                                <th>晚餐后1小时</th>
                                <th>晚餐后2小时</th>
                                <th>睡前</th>
                                <th>饮食记录</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 数据将在这里动态生成 -->
                        </tbody>
                    </table>
                </div>
                
                <div class="upload-status" id="uploadStatus"></div>
                <div class="loader" id="uploadLoader"></div>
                <button id="uploadDataBtn" class="btn btn-info" style="margin-top: 15px; display: none;">上传数据到服务器</button>
            </div>
        </div>
        
        <!-- 数据分析视图 -->
        <div id="dataAnalysis" class="view">
            <div class="card">
                <h3>血糖趋势分析</h3>
                <div class="form-group">
                    <label for="selectUserForAnalysis">选择客户</label>
                    <select id="selectUserForAnalysis">
                        <option value="">请选择客户</option>
                    </select>
                </div>
                
                <div class="tab-nav">
                    <div class="tab-link active" data-tab="breakfastTab">早餐</div>
                    <div class="tab-link" data-tab="lunchTab">午餐</div>
                    <div class="tab-link" data-tab="dinnerTab">晚餐</div>
                    <div class="tab-link" data-tab="allTab">全部数据</div>
                </div>
                
                <div class="tab-content">
                    <div id="breakfastTab" class="tab-pane active">
                        <div class="chart-container">
                            <canvas id="breakfastChart"></canvas>
                        </div>
                    </div>
                    <div id="lunchTab" class="tab-pane">
                        <div class="chart-container">
                            <canvas id="lunchChart"></canvas>
                        </div>
                    </div>
                    <div id="dinnerTab" class="tab-pane">
                        <div class="chart-container">
                            <canvas id="dinnerChart"></canvas>
                        </div>
                    </div>
                    <div id="allTab" class="tab-pane">
                        <div class="chart-container">
                            <canvas id="allDataChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 系统设置视图 -->
        <div id="settingsView" class="view">
            <div class="card">
                <h3>系统设置</h3>
                
                <div class="server-settings">
                    <h4>服务器设置</h4>
                    <div class="form-group">
                        <label for="serverUrl">服务器地址</label>
                        <input type="text" id="serverUrl" placeholder="请输入服务器API地址">
                    </div>
                    <div class="form-group">
                        <label for="apiKey">API密钥</label>
                        <input type="password" id="apiKey" placeholder="请输入API密钥">
                    </div>
                    <button id="saveServerSettingsBtn" class="btn">保存服务器设置</button>
                    <div class="upload-status" id="serverSettingsStatus"></div>
                </div>
                
                <div class="settings-group">
                    <h4>修改管理员密码</h4>
                    <div class="form-group">
                        <label for="currentPassword">当前密码</label>
                        <input type="password" id="currentPassword" placeholder="请输入当前密码">
                    </div>
                    <div class="form-group">
                        <label for="newPassword">新密码</label>
                        <input type="password" id="newPassword" placeholder="请输入新密码">
                    </div>
                    <div class="form-group">
                        <label for="confirmPassword">确认新密码</label>
                        <input type="password" id="confirmPassword" placeholder="请再次输入新密码">
                    </div>
                    <button id="changePasswordBtn" class="btn btn-warning">修改密码</button>
                </div>
                
                <div class="settings-group">
                    <h4>数据管理</h4>
                    <p>导出或清除系统数据</p>
                    <button id="exportDataBtn" class="btn">导出数据</button>
                    <button id="clearDataBtn" class="btn btn-danger" style="margin-left: 10px;">清除所有数据</button>
                </div>

                <div class="settings-group">
                    <h4>二维码访问设置</h4>
                    <div class="form-group">
                        <label for="baseUrl">自定义基础URL</label>
                        <input type="text" id="baseUrl" placeholder="留空则使用当前页面URL">
                        <small>如果二维码无法访问，请在此处填写完整的HTTP地址（如：http://您的域名.com/）</small>
                    </div>
                    <button id="testQrBtn" class="btn btn-info">测试二维码访问</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 客户填写界面 -->
    <div id="clientFormView" class="container" style="display: none; max-width: 800px;">
        <header>
            <h2 id="clientNameDisplay">血糖数据记录</h2>
            <p>请填写您的血糖数据</p>
        </header>
        
        <div style="padding: 20px;">
            <div id="clientError" class="wechat-tip" style="display: none;">
                <strong>错误：</strong> 无效的客户链接，请检查二维码是否正确。
            </div>
            
            <div class="wechat-tip" id="clientWelcomeTip">
                <strong>提示：</strong> 如果您是通过微信扫码打开此页面，请点击右上角的"..."，然后选择"在浏览器打开"以获得最佳体验。
            </div>
            
            <!-- 客户数据查看区域 -->
            <div class="client-data-view" id="clientDataView" style="display: none;">
                <h3>您的历史记录</h3>
                <div class="data-section">
                    <table class="client-data-table" id="clientDataTable">
                        <thead>
                            <tr>
                                <th>日期</th>
                                <th>空腹血糖</th>
                                <th>早餐后1小时</th>
                                <th>早餐后2小时</th>
                                <th>午餐前</th>
                                <th>午餐后1小时</th>
                                <th>午餐后2小时</th>
                                <th>晚餐前</th>
                                <th>晚餐后1小时</th>
                                <th>晚餐后2小时</th>
                                <th>睡前</th>
                                <th>饮食记录</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 客户数据将在这里动态生成 -->
                        </tbody>
                    </table>
                </div>
            </div>
            
            <form id="bloodSugarForm">
                <input type="hidden" id="clientId">
                
                <div class="form-group">
                    <label for="recordDate">日期</label>
                    <input type="date" id="recordDate" required>
                </div>
                
                <div class="data-section">
                    <h4>早餐数据</h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label for="fasting">空腹血糖 (mmol/L)</label>
                            <input type="number" step="0.1" id="fasting" placeholder="如: 5.6">
                        </div>
                        <div class="form-group">
                            <label for="breakfastAfter1">早餐后1小时 (mmol/L)</label>
                            <input type="number" step="0.1" id="breakfastAfter1" placeholder="如: 7.8">
                        </div>
                        <div class="form-group">
                            <label for="breakfastAfter2">早餐后2小时 (mmol/L)</label>
                            <input type="number" step="0.1" id="breakfastAfter2" placeholder="如: 6.5">
                        </div>
                    </div>
                </div>
                
                <div class="data-section">
                    <h4>午餐数据</h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label for="lunchBefore">午餐前 (mmol/L)</label>
                            <input type="number" step="0.1" id="lunchBefore" placeholder="如: 5.2">
                        </div>
                        <div class="form-group">
                            <label for="lunchAfter1">午餐后1小时 (mmol/L)</label>
                            <input type="number" step="0.1" id="lunchAfter1" placeholder="如: 7.5">
                        </div>
                        <div class="form-group">
                            <label for="lunchAfter2">午餐后2小时 (mmol/L)</label>
                            <input type="number" step="0.1" id="lunchAfter2" placeholder="如: 6.8">
                        </div>
                    </div>
                </div>
                
                <div class="data-section">
                    <h4>晚餐数据</h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label for="dinnerBefore">晚餐前 (mmol/L)</label>
                            <input type="number" step="0.1" id="dinnerBefore" placeholder="如: 5.4">
                        </div>
                        <div class="form-group">
                            <label for="dinnerAfter1">晚餐后1小时 (mmol/L)</label>
                            <input type="number" step="0.1" id="dinnerAfter1" placeholder="如: 7.2">
                        </div>
                        <div class="form-group">
                            <label for="dinnerAfter2">晚餐后2小时 (mmol/L)</label>
                            <input type="number" step="0.1" id="dinnerAfter2" placeholder="如: 6.9">
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="bedtime">睡前血糖 (mmol/L)</label>
                    <input type="number" step="0.1" id="bedtime" placeholder="如: 6.2">
                </div>
                
                <div class="form-group">
                    <label for="diet">饮食记录</label>
                    <textarea id="diet" rows="3" placeholder="记录当天饮食情况"></textarea>
                </div>
                
                <button type="submit" class="btn" style="width: 100%">提交数据</button>
                <div class="upload-status" id="clientUploadStatus"></div>
            </form>
        </div>
    </div>
    
    <!-- 二维码模态框 -->
    <div id="qrModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h3 id="modalUserName">客户的专属二维码</h3>
            <div class="wechat-tip">
                <strong>微信识别提示：</strong> 长按二维码图片，选择"识别图中的二维码"
            </div>
            <div id="bigQr" class="qr-code"></div>
            <div id="qrUrlDisplay" style="margin: 10px 0; padding: 10px; background: #f5f5f5; border-radius: 4px; word-break: break-all; font-size: 14px;"></div>
            <div style="margin-top: 15px;">
                <button id="downloadQrBtn" class="btn btn-success">下载二维码图片</button>
                <button id="copyUrlBtn" class="btn btn-info" style="margin-left: 10px;">复制链接</button>
            </div>
            <p style="margin-top: 20px; color: #666;">
                保存图片发给客户，客户扫码即可填写血糖数据
            </p>
        </div>
    </div>

    <!-- 编辑记录模态框 -->
    <div id="editRecordModal" class="modal">
        <div class="edit-modal-content">
            <span class="close">&times;</span>
            <h3>编辑血糖记录</h3>
            <form id="editRecordForm">
                <input type="hidden" id="editRecordId">
                <input type="hidden" id="editRecordUserId">
                
                <div class="form-group">
                    <label for="editRecordDate">日期</label>
                    <input type="date" id="editRecordDate" required>
                </div>
                
                <div class="data-section">
                    <h4>早餐数据</h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label for="editFasting">空腹血糖 (mmol/L)</label>
                            <input type="number" step="0.1" id="editFasting" placeholder="如: 5.6">
                        </div>
                        <div class="form-group">
                            <label for="editBreakfastAfter1">早餐后1小时 (mmol/L)</label>
                            <input type="number" step="0.1" id="editBreakfastAfter1" placeholder="如: 7.8">
                        </div>
                        <div class="form-group">
                            <label for="editBreakfastAfter2">早餐后2小时 (mmol/L)</label>
                            <input type="number" step="0.1" id="editBreakfastAfter2" placeholder="如: 6.5">
                        </div>
                    </div>
                </div>
                
                <div class="data-section">
                    <h4>午餐数据</h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label for="editLunchBefore">午餐前 (mmol/L)</label>
                            <input type="number" step="0.1" id="editLunchBefore" placeholder="如: 5.2">
                        </div>
                        <div class="form-group">
                            <label for="editLunchAfter1">午餐后1小时 (mmol/L)</label>
                            <input type="number" step="0.1" id="editLunchAfter1" placeholder="如: 7.5">
                        </div>
                        <div class="form-group">
                            <label for="editLunchAfter2">午餐后2小时 (mmol/L)</label>
                            <input type="number" step="0.1" id="editLunchAfter2" placeholder="如: 6.8">
                        </div>
                    </div>
                </div>
                
                <div class="data-section">
                    <h4>晚餐数据</h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label for="editDinnerBefore">晚餐前 (mmol/L)</label>
                            <input type="number" step="0.1" id="editDinnerBefore" placeholder="如: 5.4">
                        </div>
                        <div class="form-group">
                            <label for="editDinnerAfter1">晚餐后1小时 (mmol/L)</label>
                            <input type="number" step="0.1" id="editDinnerAfter1" placeholder="如: 7.2">
                        </div>
                        <div class="form-group">
                            <label for="editDinnerAfter2">晚餐后2小时 (mmol/L)</label>
                            <input type="number" step="0.1" id="editDinnerAfter2" placeholder="如: 6.9">
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="editBedtime">睡前血糖 (mmol/L)</label>
                    <input type="number" step="0.1" id="editBedtime" placeholder="如: 6.2">
                </div>
                
                <div class="form-group">
                    <label for="editDiet">饮食记录</label>
                    <textarea id="editDiet" rows="3" placeholder="记录当天饮食情况"></textarea>
                </div>
                
                <button type="submit" class="btn">保存修改</button>
                <button type="button" class="btn btn-danger" id="cancelEditBtn" style="margin-left: 10px;">取消</button>
            </form>
        </div>
    </div>

    <!-- 加载外部库 -->
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <script>
        // 初始化数据
        let users = JSON.parse(localStorage.getItem('bloodSugarUsers')) || [];
        let records = JSON.parse(localStorage.getItem('bloodSugarRecords')) || [];
        let adminPassword = localStorage.getItem('bloodSugarAdminPassword') || 'admin';
        let serverSettings = JSON.parse(localStorage.getItem('bloodSugarServerSettings')) || {
            serverUrl: '',
            apiKey: '',
            baseUrl: ''
        };
        
        // DOM元素
        const loginView = document.getElementById('loginView');
        const appView = document.getElementById('appView');
        const clientFormView = document.getElementById('clientFormView');
        const qrModal = document.getElementById('qrModal');
        const editRecordModal = document.getElementById('editRecordModal');
        
        // 设置当前日期
        document.getElementById('recordDate').valueAsDate = new Date();
        
        // 初始化服务器设置
        document.getElementById('serverUrl').value = serverSettings.serverUrl || '';
        document.getElementById('apiKey').value = serverSettings.apiKey || '';
        document.getElementById('baseUrl').value = serverSettings.baseUrl || '';
        
        // 登录功能
        document.getElementById('loginBtn').addEventListener('click', function() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            if (username === 'admin' && password === adminPassword) {
                loginView.style.display = 'none';
                appView.style.display = 'block';
                loadUsers();
                updateUserSelectors();
            } else {
                alert('用户名或密码错误');
            }
        });
        
        // 退出功能
        document.getElementById('logoutBtn').addEventListener('click', function() {
            appView.style.display = 'none';
            loginView.style.display = 'block';
            // 清空密码字段
            document.getElementById('password').value = '';
        });
        
        // 导航切换
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', function() {
                // 更新导航状态
                document.querySelectorAll('.nav-item').forEach(i => i.classList.remove('active'));
                this.classList.add('active');
                
                // 显示对应视图
                const viewId = this.getAttribute('data-view');
                document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
                document.getElementById(viewId).classList.add('active');
                
                // 如果是数据分析视图，重新加载图表
                if (viewId === 'dataAnalysis') {
                    const selectedUserId = document.getElementById('selectUserForAnalysis').value;
                    if (selectedUserId) {
                        analyzeUserData(selectedUserId);
                    }
                }
                
                // 如果是数据查看视图，显示上传按钮
                if (viewId === 'dataView' && serverSettings.serverUrl) {
                    document.getElementById('uploadDataBtn').style.display = 'block';
                } else {
                    document.getElementById('uploadDataBtn').style.display = 'none';
                }
            });
        });
        
        // 选项卡切换
        document.querySelectorAll('.tab-link').forEach(tab => {
            tab.addEventListener('click', function() {
                const tabId = this.getAttribute('data-tab');
                
                // 更新选项卡状态
                document.querySelectorAll('.tab-link').forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                
                // 显示对应内容
                document.querySelectorAll('.tab-pane').forEach(pane => pane.classList.remove('active'));
                document.getElementById(tabId).classList.add('active');
                
                // 重新加载对应图表
                const selectedUserId = document.getElementById('selectUserForAnalysis').value;
                if (selectedUserId) {
                    analyzeUserData(selectedUserId);
                }
            });
        });
        
        // 添加客户
        document.getElementById('addUserBtn').addEventListener('click', function() {
            const userName = document.getElementById('newUserName').value.trim();
            if (!userName) {
                alert('请输入客户姓名');
                return;
            }
            
            const userId = 'user_' + Date.now();
            users.push({ id: userId, name: userName });
            localStorage.setItem('bloodSugarUsers', JSON.stringify(users));
            
            document.getElementById('newUserName').value = '';
            loadUsers();
            updateUserSelectors();
            
            alert(`客户 "${userName}" 添加成功！`);
        });
        
        // 加载客户列表
        function loadUsers() {
            const userList = document.getElementById('userList');
            userList.innerHTML = '';
            
            if (users.length === 0) {
                userList.innerHTML = '<p style="text-align: center; padding: 20px; color: #666;">暂无客户，请添加客户</p>';
                return;
            }
            
            users.forEach(user => {
                const userCard = document.createElement('div');
                userCard.className = 'user-card';
                
                // 计算该用户的记录数量
                const recordCount = records.filter(r => r.userId === user.id).length;
                
                userCard.innerHTML = `
                    <h4>${user.name}</h4>
                    <p>记录数: ${recordCount}</p>
                    <div class="qr-code">
                        <canvas id="qr-${user.id}" width="120" height="120"></canvas>
                    </div>
                    <button class="btn view-qr" data-id="${user.id}" style="width: 100%; margin-top: 10px;">查看二维码</button>
                    <button class="btn btn-danger delete-user" data-id="${user.id}" style="width: 100%; margin-top: 5px;">删除客户</button>
                `;
                
                userList.appendChild(userCard);
                
                // 生成二维码
                const qrUrl = generateClientUrl(user.id);
                const qrCanvas = document.getElementById(`qr-${user.id}`);
                
                QRCode.toCanvas(qrCanvas, qrUrl, { 
                    width: 120,
                    margin: 1,
                    color: {
                        dark: '#000000',
                        light: '#FFFFFF'
                    }
                }, function(error) {
                    if (error) console.error(error);
                });
            });
            
            // 添加查看二维码事件
            document.querySelectorAll('.view-qr').forEach(btn => {
                btn.addEventListener('click', function() {
                    const userId = this.getAttribute('data-id');
                    const user = users.find(u => u.id === userId);
                    
                    document.getElementById('modalUserName').textContent = user.name + ' 的专属二维码';
                    
                    // 生成大二维码
                    const qrUrl = generateClientUrl(userId);
                    const bigQr = document.getElementById('bigQr');
                    bigQr.innerHTML = '';
                    
                    // 显示URL
                    document.getElementById('qrUrlDisplay').textContent = qrUrl;
                    
                    QRCode.toCanvas(bigQr, qrUrl, { 
                        width: 200,
                        margin: 1,
                        color: {
                            dark: '#000000',
                            light: '#FFFFFF'
                        }
                    }, function(error) {
                        if (error) console.error(error);
                    });
                    
                    // 显示模态框
                    qrModal.style.display = 'flex';
                });
            });
            
            // 添加删除客户事件
            document.querySelectorAll('.delete-user').forEach(btn => {
                btn.addEventListener('click', function() {
                    const userId = this.getAttribute('data-id');
                    const user = users.find(u => u.id === userId);
                    
                    if (confirm(`确定要删除客户 "${user.name}" 吗？此操作将同时删除该客户的所有记录！`)) {
                        // 删除客户
                        users = users.filter(u => u.id !== userId);
                        localStorage.setItem('bloodSugarUsers', JSON.stringify(users));
                        
                        // 删除相关记录
                        records = records.filter(r => r.userId !== userId);
                        localStorage.setItem('bloodSugarRecords', JSON.stringify(records));
                        
                        // 重新加载
                        loadUsers();
                        updateUserSelectors();
                        
                        alert(`客户 "${user.name}" 已删除`);
                    }
                });
            });
        }
        
        // 生成客户端URL
        function generateClientUrl(userId) {
            let baseUrl = serverSettings.baseUrl || '';
            
            // 如果没有设置基础URL，使用当前页面URL
            if (!baseUrl) {
                baseUrl = window.location.href.split('?')[0];
            } else {
                // 确保baseUrl以/结尾
                if (!baseUrl.endsWith('/')) {
                    baseUrl += '/';
                }
                // 添加文件名（如果baseUrl是目录）
                if (!baseUrl.includes('.html')) {
                    const currentFilename = window.location.pathname.split('/').pop();
                    if (currentFilename) {
                        baseUrl += currentFilename;
                    } else {
                        baseUrl += 'index.html';
                    }
                }
            }
            
            return baseUrl + '?user=' + userId;
        }
        
        // 更新用户选择器
        function updateUserSelectors() {
            const selectUser = document.getElementById('selectUser');
            const selectUserForAnalysis = document.getElementById('selectUserForAnalysis');
            
            // 清空并重新添加选项
            selectUser.innerHTML = '<option value="">请选择客户</option>';
            selectUserForAnalysis.innerHTML = '<option value="">请选择客户</option>';
            
            users.forEach(user => {
                const option1 = document.createElement('option');
                option1.value = user.id;
                option1.textContent = user.name;
                selectUser.appendChild(option1);
                
                const option2 = document.createElement('option');
                option2.value = user.id;
                option2.textContent = user.name;
                selectUserForAnalysis.appendChild(option2);
            });
            
            // 如果有服务器设置，显示上传按钮
            if (serverSettings.serverUrl) {
                document.getElementById('uploadDataBtn').style.display = 'block';
            }
        }
        
        // 选择客户查看数据
        document.getElementById('selectUser').addEventListener('change', function() {
            const userId = this.value;
            loadUserData(userId);
        });
        
        // 加载用户数据
        function loadUserData(userId) {
            const tbody = document.querySelector('#dataTable tbody');
            tbody.innerHTML = '';
            
            if (!userId) {
                tbody.innerHTML = '<tr><td colspan="13" style="text-align: center; padding: 20px; color: #666;">请选择客户</td></tr>';
                return;
            }
            
            // 获取该用户的所有记录并按日期排序
            const userRecords = records
                .filter(record => record.userId === userId)
                .sort((a, b) => new Date(b.date) - new Date(a.date));
            
            if (userRecords.length === 0) {
                tbody.innerHTML = '<tr><td colspan="13" style="text-align: center; padding: 20px; color: #666;">该客户暂无数据</td></tr>';
                return;
            }
            
            // 显示数据
            userRecords.forEach(record => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${record.date}</td>
                    <td>${record.fasting || '-'}</td>
                    <td>${record.breakfastAfter1 || '-'}</td>
                    <td>${record.breakfastAfter2 || '-'}</td>
                    <td>${record.lunchBefore || '-'}</td>
                    <td>${record.lunchAfter1 || '-'}</td>
                    <td>${record.lunchAfter2 || '-'}</td>
                    <td>${record.dinnerBefore || '-'}</td>
                    <td>${record.dinnerAfter1 || '-'}</td>
                    <td>${record.dinnerAfter2 || '-'}</td>
                    <td>${record.bedtime || '-'}</td>
                    <td>${record.diet || '-'}</td>
                    <td>
                        <button class="btn btn-warning btn-sm edit-record" data-id="${record.id}">修改</button>
                        <button class="btn btn-danger btn-sm delete-record" data-id="${record.id}">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
            
            // 添加编辑记录事件
            document.querySelectorAll('.edit-record').forEach(btn => {
                btn.addEventListener('click', function() {
                    const recordId = this.getAttribute('data-id');
                    const record = records.find(r => r.id === recordId);
                    
                    if (record) {
                        // 填充编辑表单
                        document.getElementById('editRecordId').value = record.id;
                        document.getElementById('editRecordUserId').value = record.userId;
                        document.getElementById('editRecordDate').value = record.date;
                        document.getElementById('editFasting').value = record.fasting || '';
                        document.getElementById('editBreakfastAfter1').value = record.breakfastAfter1 || '';
                        document.getElementById('editBreakfastAfter2').value = record.breakfastAfter2 || '';
                        document.getElementById('editLunchBefore').value = record.lunchBefore || '';
                        document.getElementById('editLunchAfter1').value = record.lunchAfter1 || '';
                        document.getElementById('editLunchAfter2').value = record.lunchAfter2 || '';
                        document.getElementById('editDinnerBefore').value = record.dinnerBefore || '';
                        document.getElementById('editDinnerAfter1').value = record.dinnerAfter1 || '';
                        document.getElementById('editDinnerAfter2').value = record.dinnerAfter2 || '';
                        document.getElementById('editBedtime').value = record.bedtime || '';
                        document.getElementById('editDiet').value = record.diet || '';
                        
                        // 显示编辑模态框
                        editRecordModal.style.display = 'flex';
                    }
                });
            });
            
            // 添加删除记录事件
            document.querySelectorAll('.delete-record').forEach(btn => {
                btn.addEventListener('click', function() {
                    const recordId = this.getAttribute('data-id');
                    const record = records.find(r => r.id === recordId);
                    
                    if (confirm('确定要删除这条记录吗？')) {
                        records = records.filter(r => r.id !== recordId);
                        localStorage.setItem('bloodSugarRecords', JSON.stringify(records));
                        
                        // 重新加载数据
                        loadUserData(userId);
                        alert('记录已删除');
                    }
                });
            });
        }
        
        // 编辑记录表单提交
        document.getElementById('editRecordForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const recordId = document.getElementById('editRecordId').value;
            const userId = document.getElementById('editRecordUserId').value;
            const date = document.getElementById('editRecordDate').value;
            const fasting = document.getElementById('editFasting').value;
            const breakfastAfter1 = document.getElementById('editBreakfastAfter1').value;
            const breakfastAfter2 = document.getElementById('editBreakfastAfter2').value;
            const lunchBefore = document.getElementById('editLunchBefore').value;
            const lunchAfter1 = document.getElementById('editLunchAfter1').value;
            const lunchAfter2 = document.getElementById('editLunchAfter2').value;
            const dinnerBefore = document.getElementById('editDinnerBefore').value;
            const dinnerAfter1 = document.getElementById('editDinnerAfter1').value;
            const dinnerAfter2 = document.getElementById('editDinnerAfter2').value;
            const bedtime = document.getElementById('editBedtime').value;
            const diet = document.getElementById('editDiet').value;
            
            // 找到记录索引
            const recordIndex = records.findIndex(r => r.id === recordId);
            if (recordIndex === -1) {
                alert('记录不存在');
                return;
            }
            
            // 更新记录
            records[recordIndex] = {
                ...records[recordIndex],
                date: date,
                fasting: fasting || null,
                breakfastAfter1: breakfastAfter1 || null,
                breakfastAfter2: breakfastAfter2 || null,
                lunchBefore: lunchBefore || null,
                lunchAfter1: lunchAfter1 || null,
                lunchAfter2: lunchAfter2 || null,
                dinnerBefore: dinnerBefore || null,
                dinnerAfter1: dinnerAfter1 || null,
                dinnerAfter2: dinnerAfter2 || null,
                bedtime: bedtime || null,
                diet: diet || ''
            };
            
            // 保存到本地存储
            localStorage.setItem('bloodSugarRecords', JSON.stringify(records));
            
            // 关闭模态框
            editRecordModal.style.display = 'none';
            
            // 重新加载当前用户的数据
            loadUserData(userId);
            
            alert('修改成功！');
        });
        
        // 取消编辑
        document.getElementById('cancelEditBtn').addEventListener('click', function() {
            editRecordModal.style.display = 'none';
        });
        
        // 选择客户进行分析
        document.getElementById('selectUserForAnalysis').addEventListener('change', function() {
            const userId = this.value;
            analyzeUserData(userId);
        });
        
        // 分析用户数据并生成图表
        function analyzeUserData(userId) {
            const breakfastCtx = document.getElementById('breakfastChart');
            const lunchCtx = document.getElementById('lunchChart');
            const dinnerCtx = document.getElementById('dinnerChart');
            const allCtx = document.getElementById('allDataChart');
            
            if (!userId) {
                [breakfastCtx, lunchCtx, dinnerCtx, allCtx].forEach(ctx => {
                    if (ctx) {
                        const chartInstance = Chart.getChart(ctx);
                        if (chartInstance) {
                            chartInstance.destroy();
                        }
                    }
                });
                return;
            }
            
            // 获取该用户的所有记录并按日期排序
            const userRecords = records
                .filter(record => record.userId === userId)
                .sort((a, b) => new Date(a.date) - new Date(b.date));
            
            if (userRecords.length === 0) {
                [breakfastCtx, lunchCtx, dinnerCtx, allCtx].forEach(ctx => {
                    if (ctx) {
                        const chartInstance = Chart.getChart(ctx);
                        if (chartInstance) {
                            chartInstance.destroy();
                        }
                    }
                });
                return;
            }
            
            // 准备图表数据
            const dates = userRecords.map(r => r.date);
            
            // 早餐数据
            const fastingData = userRecords.map(r => r.fasting || null);
            const breakfastAfter1Data = userRecords.map(r => r.breakfastAfter1 || null);
            const breakfastAfter2Data = userRecords.map(r => r.breakfastAfter2 || null);
            
            // 午餐数据
            const lunchBeforeData = userRecords.map(r => r.lunchBefore || null);
            const lunchAfter1Data = userRecords.map(r => r.lunchAfter1 || null);
            const lunchAfter2Data = userRecords.map(r => r.lunchAfter2 || null);
            
            // 晚餐数据
            const dinnerBeforeData = userRecords.map(r => r.dinnerBefore || null);
            const dinnerAfter1Data = userRecords.map(r => r.dinnerAfter1 || null);
            const dinnerAfter2Data = userRecords.map(r => r.dinnerAfter2 || null);
            
            // 睡前数据
            const bedtimeData = userRecords.map(r => r.bedtime || null);
            
            // 销毁现有图表实例
            [breakfastCtx, lunchCtx, dinnerCtx, allCtx].forEach(ctx => {
                if (ctx) {
                    const chartInstance = Chart.getChart(ctx);
                    if (chartInstance) {
                        chartInstance.destroy();
                    }
                }
            });
            
            // 早餐图表
            if (breakfastCtx) {
                new Chart(breakfastCtx, {
                    type: 'line',
                    data: {
                        labels: dates,
                        datasets: [
                            {
                                label: '空腹血糖',
                                data: fastingData,
                                borderColor: 'rgb(255, 99, 132)',
                                backgroundColor: 'rgba(255, 99, 132, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '早餐后1小时',
                                data: breakfastAfter1Data,
                                borderColor: 'rgb(54, 162, 235)',
                backgroundColor: 'rgba(54, 162, 235, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '早餐后2小时',
                                data: breakfastAfter2Data,
                                borderColor: 'rgb(75, 192, 192)',
                                backgroundColor: 'rgba(75, 192, 192, 0.1)',
                                tension: 0.1,
                                fill: false
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: false,
                                suggestedMin: 3,
                                suggestedMax: 10,
                                title: {
                                    display: true,
                                    text: '血糖值 (mmol/L)'
                                }
                            }
                        }
                    }
                });
            }
            
            // 午餐图表
            if (lunchCtx) {
                new Chart(lunchCtx, {
                    type: 'line',
                    data: {
                        labels: dates,
                        datasets: [
                            {
                                label: '午餐前',
                                data: lunchBeforeData,
                                borderColor: 'rgb(255, 159, 64)',
                                backgroundColor: 'rgba(255, 159, 64, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '午餐后1小时',
                                data: lunchAfter1Data,
                                borderColor: 'rgb(153, 102, 255)',
                                backgroundColor: 'rgba(153, 102, 255, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '午餐后2小时',
                                data: lunchAfter2Data,
                                borderColor: 'rgb(255, 205, 86)',
                                backgroundColor: 'rgba(255, 205, 86, 0.1)',
                                tension: 0.1,
                                fill: false
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: false,
                                suggestedMin: 3,
                                suggestedMax: 10,
                                title: {
                                    display: true,
                                    text: '血糖值 (mmol/L)'
                                }
                            }
                        }
                    }
                });
            }
            
            // 晚餐图表
            if (dinnerCtx) {
                new Chart(dinnerCtx, {
                    type: 'line',
                    data: {
                        labels: dates,
                        datasets: [
                            {
                                label: '晚餐前',
                                data: dinnerBeforeData,
                                borderColor: 'rgb(201, 203, 207)',
                                backgroundColor: 'rgba(201, 203, 207, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '晚餐后1小时',
                                data: dinnerAfter1Data,
                                borderColor: 'rgb(255, 99, 132)',
                                backgroundColor: 'rgba(255, 99, 132, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '晚餐后2小时',
                                data: dinnerAfter2Data,
                                borderColor: 'rgb(54, 162, 235)',
                                backgroundColor: 'rgba(54, 162, 235, 0.1)',
                                tension: 0.1,
                                fill: false
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: false,
                                suggestedMin: 3,
                                suggestedMax: 10,
                                title: {
                                    display: true,
                                    text: '血糖值 (mmol/L)'
                                }
                            }
                        }
                    }
                });
            }
            
            // 全部数据图表
            if (allCtx) {
                new Chart(allCtx, {
                    type: 'line',
                    data: {
                        labels: dates,
                        datasets: [
                            {
                                label: '空腹',
                                data: fastingData,
                                borderColor: 'rgb(255, 99, 132)',
                                backgroundColor: 'rgba(255, 99, 132, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '早餐后1h',
                                data: breakfastAfter1Data,
                                borderColor: 'rgb(54, 162, 235)',
                                backgroundColor: 'rgba(54, 162, 235, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '早餐后2h',
                                data: breakfastAfter2Data,
                                borderColor: 'rgb(75, 192, 192)',
                                backgroundColor: 'rgba(75, 192, 192, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '午餐前',
                                data: lunchBeforeData,
                                borderColor: 'rgb(255, 159, 64)',
                                backgroundColor: 'rgba(255, 159, 64, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '午餐后1h',
                                data: lunchAfter1Data,
                                borderColor: 'rgb(153, 102, 255)',
                                backgroundColor: 'rgba(153, 102, 255, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '午餐后2h',
                                data: lunchAfter2Data,
                                borderColor: 'rgb(255, 205, 86)',
                                backgroundColor: 'rgba(255, 205, 86, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '晚餐前',
                                data: dinnerBeforeData,
                                borderColor: 'rgb(201, 203, 207)',
                                backgroundColor: 'rgba(201, 203, 207, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '晚餐后1h',
                                data: dinnerAfter1Data,
                                borderColor: 'rgb(255, 99, 132)',
                                backgroundColor: 'rgba(255, 99, 132, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '晚餐后2h',
                                data: dinnerAfter2Data,
                                borderColor: 'rgb(54, 162, 235)',
                                backgroundColor: 'rgba(54, 162, 235, 0.1)',
                                tension: 0.1,
                                fill: false
                            },
                            {
                                label: '睡前',
                                data: bedtimeData,
                                borderColor: 'rgb(75, 192, 192)',
                                backgroundColor: 'rgba(75, 192, 192, 0.1)',
                                tension: 0.1,
                                fill: false
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: false,
                                suggestedMin: 3,
                                suggestedMax: 10,
                                title: {
                                    display: true,
                                    text: '血糖值 (mmol/L)'
                                }
                            }
                        }
                    }
                });
            }
        }
        
        // 客户提交血糖数据
        document.getElementById('bloodSugarForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const userId = document.getElementById('clientId').value;
            const date = document.getElementById('recordDate').value;
            const fasting = document.getElementById('fasting').value;
            const breakfastAfter1 = document.getElementById('breakfastAfter1').value;
            const breakfastAfter2 = document.getElementById('breakfastAfter2').value;
            const lunchBefore = document.getElementById('lunchBefore').value;
            const lunchAfter1 = document.getElementById('lunchAfter1').value;
            const lunchAfter2 = document.getElementById('lunchAfter2').value;
            const dinnerBefore = document.getElementById('dinnerBefore').value;
            const dinnerAfter1 = document.getElementById('dinnerAfter1').value;
            const dinnerAfter2 = document.getElementById('dinnerAfter2').value;
            const bedtime = document.getElementById('bedtime').value;
            const diet = document.getElementById('diet').value;
            
            if (!date) {
                alert('请选择日期');
                return;
            }
            
            // 检查是否已有当天记录
            const existingIndex = records.findIndex(r => r.userId === userId && r.date === date);
            
            if (existingIndex >= 0) {
                // 更新现有记录
                const existingRecord = records[existingIndex];
                records[existingIndex] = {
                    ...existingRecord,
                    fasting: fasting || existingRecord.fasting,
                    breakfastAfter1: breakfastAfter1 || existingRecord.breakfastAfter1,
                    breakfastAfter2: breakfastAfter2 || existingRecord.breakfastAfter2,
                    lunchBefore: lunchBefore || existingRecord.lunchBefore,
                    lunchAfter1: lunchAfter1 || existingRecord.lunchAfter1,
                    lunchAfter2: lunchAfter2 || existingRecord.lunchAfter2,
                    dinnerBefore: dinnerBefore || existingRecord.dinnerBefore,
                    dinnerAfter1: dinnerAfter1 || existingRecord.dinnerAfter1,
                    dinnerAfter2: dinnerAfter2 || existingRecord.dinnerAfter2,
                    bedtime: bedtime || existingRecord.bedtime,
                    diet: diet || existingRecord.diet
                };
            } else {
                // 添加新记录
                records.push({
                    id: 'record_' + Date.now(),
                    userId,
                    date,
                    fasting: fasting || null,
                    breakfastAfter1: breakfastAfter1 || null,
                    breakfastAfter2: breakfastAfter2 || null,
                    lunchBefore: lunchBefore || null,
                    lunchAfter1: lunchAfter1 || null,
                    lunchAfter2: lunchAfter2 || null,
                    dinnerBefore: dinnerBefore || null,
                    dinnerAfter1: dinnerAfter1 || null,
                    dinnerAfter2: dinnerAfter2 || null,
                    bedtime: bedtime || null,
                    diet: diet || ''
                });
            }
            
            // 保存到本地存储
            localStorage.setItem('bloodSugarRecords', JSON.stringify(records));
            
            // 显示上传状态
            const statusElement = document.getElementById('clientUploadStatus');
            statusElement.textContent = '数据提交成功！';
            statusElement.className = 'upload-status upload-success';
            statusElement.style.display = 'block';
            
            // 重新加载客户数据视图
            loadClientData(userId);
            
            // 尝试自动上传到服务器
            if (serverSettings.serverUrl) {
                uploadDataToServer(userId, function(success, message) {
                    if (success) {
                        statusElement.textContent = '数据提交并上传服务器成功！';
                        statusElement.className = 'upload-status upload-success';
                    } else {
                        statusElement.textContent = '数据提交成功，但上传服务器失败: ' + message;
                        statusElement.className = 'upload-status upload-error';
                    }
                    statusElement.style.display = 'block';
                });
            }
            
            // 3秒后隐藏状态提示
            setTimeout(() => {
                statusElement.style.display = 'none';
            }, 3000);
            
            // 重置表单
            this.reset();
            document.getElementById('recordDate').valueAsDate = new Date();
        });
        
        // 加载客户数据（只显示当前客户的数据）
        function loadClientData(userId) {
            const tbody = document.querySelector('#clientDataTable tbody');
            tbody.innerHTML = '';
            
            // 获取该用户的所有记录并按日期排序
            const userRecords = records
                .filter(record => record.userId === userId)
                .sort((a, b) => new Date(b.date) - new Date(a.date));
            
            if (userRecords.length === 0) {
                tbody.innerHTML = '<tr><td colspan="12" class="no-data">暂无数据记录</td></tr>';
                return;
            }
            
            // 显示数据
            userRecords.forEach(record => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${record.date}</td>
                    <td>${record.fasting || '-'}</td>
                    <td>${record.breakfastAfter1 || '-'}</td>
                    <td>${record.breakfastAfter2 || '-'}</td>
                    <td>${record.lunchBefore || '-'}</td>
                    <td>${record.lunchAfter1 || '-'}</td>
                    <td>${record.lunchAfter2 || '-'}</td>
                    <td>${record.dinnerBefore || '-'}</td>
                    <td>${record.dinnerAfter1 || '-'}</td>
                    <td>${record.dinnerAfter2 || '-'}</td>
                    <td>${record.bedtime || '-'}</td>
                    <td>${record.diet || '-'}</td>
                `;
                tbody.appendChild(row);
            });
            
            // 显示客户数据视图
            document.getElementById('clientDataView').style.display = 'block';
        }
        
        // 修改密码功能
        document.getElementById('changePasswordBtn').addEventListener('click', function() {
            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            if (!currentPassword || !newPassword || !confirmPassword) {
                alert('请填写所有密码字段');
                return;
            }
            
            if (currentPassword !== adminPassword) {
                alert('当前密码不正确');
                return;
            }
            
            if (newPassword !== confirmPassword) {
                alert('新密码和确认密码不匹配');
                return;
            }
            
            if (newPassword.length < 4) {
                alert('新密码长度不能少于4位');
                return;
            }
            
            adminPassword = newPassword;
            localStorage.setItem('bloodSugarAdminPassword', adminPassword);
            
            alert('密码修改成功！');
            
            // 清空密码字段
            document.getElementById('currentPassword').value = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmPassword').value = '';
        });
        
        // 导出数据功能
        document.getElementById('exportDataBtn').addEventListener('click', function() {
            const dataStr = JSON.stringify({
                users: users,
                records: records
            }, null, 2);
            
            const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
            
            const exportFileDefaultName = `blood_sugar_data_${new Date().toISOString().slice(0,10)}.json`;
            
            const linkElement = document.createElement('a');
            linkElement.setAttribute('href', dataUri);
            linkElement.setAttribute('download', exportFileDefaultName);
            linkElement.click();
        });
        
        // 清除数据功能
        document.getElementById('clearDataBtn').addEventListener('click', function() {
            if (confirm('确定要清除所有数据吗？此操作不可恢复！')) {
                localStorage.removeItem('bloodSugarUsers');
                localStorage.removeItem('bloodSugarRecords');
                users = [];
                records = [];
                
                alert('所有数据已清除');
                loadUsers();
                updateUserSelectors();
            }
        });
        
        // 保存服务器设置
        document.getElementById('saveServerSettingsBtn').addEventListener('click', function() {
            const serverUrl = document.getElementById('serverUrl').value.trim();
            const apiKey = document.getElementById('apiKey').value.trim();
            const baseUrl = document.getElementById('baseUrl').value.trim();
            
            if (!serverUrl) {
                alert('请输入服务器地址');
                return;
            }
            
            serverSettings = {
                serverUrl: serverUrl,
                apiKey: apiKey,
                baseUrl: baseUrl
            };
            
            localStorage.setItem('bloodSugarServerSettings', JSON.stringify(serverSettings));
            
            const statusElement = document.getElementById('serverSettingsStatus');
            statusElement.textContent = '服务器设置已保存！';
            statusElement.className = 'upload-status upload-success';
            statusElement.style.display = 'block';
            
            // 显示上传按钮
            document.getElementById('uploadDataBtn').style.display = 'block';
            
            // 3秒后隐藏状态提示
            setTimeout(() => {
                statusElement.style.display = 'none';
            }, 3000);
        });
        
        // 上传数据到服务器
        document.getElementById('uploadDataBtn').addEventListener('click', function() {
            const userId = document.getElementById('selectUser').value;
            
            if (!userId) {
                alert('请先选择客户');
                return;
            }
            
            if (!serverSettings.serverUrl) {
                alert('请先在系统设置中配置服务器地址');
                return;
            }
            
            uploadDataToServer(userId, function(success, message) {
                const statusElement = document.getElementById('uploadStatus');
                const loader = document.getElementById('uploadLoader');
                
                loader.style.display = 'none';
                
                if (success) {
                    statusElement.textContent = '数据上传成功！';
                    statusElement.className = 'upload-status upload-success';
                } else {
                    statusElement.textContent = '数据上传失败: ' + message;
                    statusElement.className = 'upload-status upload-error';
                }
                statusElement.style.display = 'block';
                
                // 5秒后隐藏状态提示
                setTimeout(() => {
                    statusElement.style.display = 'none';
                }, 5000);
            });
        });
        
        // 上传数据到服务器的函数
        function uploadDataToServer(userId, callback) {
            const loader = document.getElementById('uploadLoader');
            loader.style.display = 'block';
            
            // 获取用户数据
            const user = users.find(u => u.id === userId);
            if (!user) {
                loader.style.display = 'none';
                callback(false, '用户不存在');
                return;
            }
            
            // 获取用户的所有记录
            const userRecords = records.filter(r => r.userId === userId);
            
            // 准备上传的数据
            const uploadData = {
                user: user,
                records: userRecords,
                timestamp: new Date().toISOString()
            };
            
            // 模拟上传到服务器（实际使用时替换为真实的API调用）
            setTimeout(() => {
                // 这里是模拟上传，实际使用时应该使用fetch或XMLHttpRequest
                console.log('上传数据到服务器:', serverSettings.serverUrl, uploadData);
                
                // 模拟成功响应
                const success = Math.random() > 0.2; // 80%成功率模拟
                
                if (success) {
                    callback(true, '上传成功');
                } else {
                    callback(false, '服务器响应超时');
                }
            }, 1500);
            
            /* 实际服务器上传代码示例（取消注释并替换上面的setTimeout）：
            fetch(serverSettings.serverUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + serverSettings.apiKey
                },
                body: JSON.stringify(uploadData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('服务器错误: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                loader.style.display = 'none';
                callback(true, '上传成功');
            })
            .catch(error => {
                loader.style.display = 'none';
                callback(false, error.message);
            });
            */
        }
        
        // 下载二维码图片
        document.getElementById('downloadQrBtn').addEventListener('click', function() {
            const canvas = document.querySelector('#bigQr canvas');
            if (!canvas) return;
            
            const link = document.createElement('a');
            link.download = '血糖记录二维码.png';
            link.href = canvas.toDataURL('image/png');
            link.click();
        });
        
        // 复制链接
        document.getElementById('copyUrlBtn').addEventListener('click', function() {
            const url = document.getElementById('qrUrlDisplay').textContent;
            navigator.clipboard.writeText(url).then(() => {
                alert('链接已复制到剪贴板');
            }).catch(err => {
                alert('复制失败，请手动复制链接');
            });
        });
        
        // 测试二维码访问
        document.getElementById('testQrBtn').addEventListener('click', function() {
            const baseUrl = document.getElementById('baseUrl').value.trim();
            if (!baseUrl) {
                alert('请先输入基础URL');
                return;
            }
            
            // 保存设置
            serverSettings.baseUrl = baseUrl;
            localStorage.setItem('bloodSugarServerSettings', JSON.stringify(serverSettings));
            
            // 生成测试URL
            const testUrl = generateClientUrl('test_user_id');
            window.open(testUrl, '_blank');
        });
        
        // 检查URL参数，判断是否为客户扫码访问
        function checkClientAccess() {
            const urlParams = new URLSearchParams(window.location.search);
            const userId = urlParams.get('user');
            
            if (userId && userId.startsWith('user_')) {
                const user = users.find(u => u.id === userId);
                if (user) {
                    // 显示客户填写界面
                    loginView.style.display = 'none';
                    appView.style.display = 'none';
                    clientFormView.style.display = 'block';
                    document.getElementById('clientNameDisplay').textContent = user.name + ' 的血糖记录';
                    document.getElementById('clientId').value = userId;
                    
                    // 加载客户数据
                    loadClientData(userId);
                    return true;
                } else {
                    // 用户不存在，显示错误信息
                    document.getElementById('clientError').style.display = 'block';
                    document.getElementById('clientWelcomeTip').style.display = 'none';
                    document.getElementById('bloodSugarForm').style.display = 'none';
                    loginView.style.display = 'none';
                    appView.style.display = 'none';
                    clientFormView.style.display = 'block';
                    return false;
                }
            }
            
            return false;
        }
        
        // 关闭模态框
        document.querySelectorAll('.close').forEach(closeBtn => {
            closeBtn.addEventListener('click', function() {
                qrModal.style.display = 'none';
                editRecordModal.style.display = 'none';
            });
        });
        
        // 点击模态框外部关闭
        window.addEventListener('click', function(event) {
            if (event.target === qrModal) {
                qrModal.style.display = 'none';
            }
            if (event.target === editRecordModal) {
                editRecordModal.style.display = 'none';
            }
        });
        
        // 页面加载时检查
        window.addEventListener('load', function() {
            // 检查是否是客户扫码访问
            const isClient = checkClientAccess();
            
            // 如果不是客户访问，且是管理员首次使用，添加示例数据
            if (!isClient && users.length === 0) {
                // 添加示例客户
                users = [
                    { id: 'user_' + (Date.now() - 10000), name: '张三' },
                    { id: 'user_' + (Date.now() - 5000), name: '李四' }
                ];
                localStorage.setItem('bloodSugarUsers', JSON.stringify(users));
                
                // 添加示例数据
                const today = new Date().toISOString().split('T')[0];
                const yesterday = new Date(Date.now() - 86400000).toISOString().split('T')[0];
                const dayBefore = new Date(Date.now() - 172800000).toISOString().split('T')[0];
                
                records = [
                    {
                        id: 'record_1',
                        userId: users[0].id,
                        date: dayBefore,
                        fasting: 5.8,
                        breakfastAfter1: 8.5,
                        breakfastAfter2: 7.2,
                        lunchBefore: 5.2,
                        lunchAfter1: 7.8,
                        lunchAfter2: 6.9,
                        dinnerBefore: 5.4,
                        dinnerAfter1: 7.5,
                        dinnerAfter2: 6.7,
                        bedtime: 6.2,
                        diet: '早餐：牛奶+鸡蛋；午餐：米饭+青菜；晚餐：面条'
                    },
                    {
                        id: 'record_2',
                        userId: users[0].id,
                        date: yesterday,
                        fasting: 5.6,
                        breakfastAfter1: 8.2,
                        breakfastAfter2: 6.8,
                        lunchBefore: 5.1,
                        lunchAfter1: 7.6,
                        lunchAfter2: 6.5,
                        dinnerBefore: 5.3,
                        dinnerAfter1: 7.3,
                        dinnerAfter2: 6.4,
                        bedtime: 6.0,
                        diet: '早餐：粥+包子；午餐：米饭+鱼肉；晚餐：蔬菜沙拉'
                    },
                    {
                        id: 'record_3',
                        userId: users[0].id,
                        date: today,
                        fasting: 5.4,
                        breakfastAfter1: null,
                        breakfastAfter2: null,
                        lunchBefore: null,
                        lunchAfter1: null,
                        lunchAfter2: null,
                        dinnerBefore: null,
                        dinnerAfter1: null,
                        dinnerAfter2: null,
                        bedtime: null,
                        diet: '早餐：全麦面包+牛奶'
                    },
                    {
                        id: 'record_4',
                        userId: users[1].id,
                        date: yesterday,
                        fasting: 6.1,
                        breakfastAfter1: 9.2,
                        breakfastAfter2: 7.5,
                        lunchBefore: 5.8,
                        lunchAfter1: 8.5,
                        lunchAfter2: 7.2,
                        dinnerBefore: 5.9,
                        dinnerAfter1: 8.2,
                        dinnerAfter2: 7.1,
                        bedtime: 6.5,
                        diet: '早餐：面条；午餐：米饭+红烧肉；晚餐：饺子'
                    }
                ];
                localStorage.setItem('bloodSugarRecords', JSON.stringify(records));
            }
        });
    </script>
</body>
</html>